package org.example.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.example.exception.ClassHasStudentsException;
import org.example.mapper.ClazzMapper;
import org.example.pojo.Clazz;
import org.example.pojo.ClazzQueryParam;
import org.example.pojo.PageResult;
import org.example.service.ClazzService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class ClazzServiceImpl implements ClazzService {
    @Autowired
    private ClazzMapper clazzMapper;

    @Override
    public PageResult<Clazz> page(ClazzQueryParam clazzQueryParam) {
        //设置分页参数
        PageHelper.startPage(clazzQueryParam.getPage(), clazzQueryParam.getPageSize());
        //执行查询
        List<Clazz> clazzList = clazzMapper.list(clazzQueryParam);
        // 计算并设置班级状态
        LocalDate now = LocalDate.now();
        for (Clazz clazz : clazzList) {
            LocalDate beginDate = clazz.getBeginDate();
            LocalDate endDate = clazz.getEndDate();
            if (now.isBefore(beginDate)) {
                clazz.setStatus("未开班");
            } else if (now.isAfter(endDate)) {
                clazz.setStatus("已结课");
            } else {
                clazz.setStatus("在读");
            }
        }
        //封装结果
        Page<Clazz> p = (Page<Clazz>) clazzList;
        return new PageResult<Clazz>(p.getTotal(), p.getResult());
    }

    public void delete(Integer classId) {
        // 查询该班级下的学生数量
        Integer studentCount = clazzMapper.countStudentsInClass(classId);
        if (studentCount > 0) {
            // 如果班级下有学生，抛出异常
            throw new ClassHasStudentsException("对不起, 该班级下有学生, 不能直接删除");
        }
        // 班级下没有学生，执行删除操作
        clazzMapper.deleteById(classId);
    }

    @Override
    public void save(Clazz clazz) {
        //补全基础属性 - creatTime, updateTime
        clazz.setCreateTime(LocalDateTime.now());
        clazz.setUpdateTime(LocalDateTime.now());
        clazzMapper.insert(clazz);
    }

    @Override
    public void update(Clazz clazz) {
        // 补全基础属性 - updateTime
        clazz.setUpdateTime(LocalDateTime.now());
        clazzMapper.update(clazz);
    }

    @Override
    public Clazz getInfo(Integer id) {
        return clazzMapper.getById(id);
    }
}